package com.sikadwafastdaisfondturbo.pretloan.utils.http;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog;

import java.net.InetAddress;

public class HttpDns {
    public void lookupSys(String httpUrl,Http3DnsCallback callback) {
        final String HOST = httpUrl.replaceFirst("^(https?://)", "");
        new Thread(() -> {
            try {
                InetAddress[] addresses = InetAddress.getAllByName(HOST);
                for (InetAddress address : addresses) {
                    String ipAddress = address.getHostAddress();
                    if (!TextUtils.isEmpty(ipAddress)) {
                        Log.d(HttpDns.class.getSimpleName(), "lookup: " + ipAddress);
                        new Handler(Looper.getMainLooper()).post(() -> {
                            callback.onResult(ipAddress);
                        });
                        break;
                    }
                }
            } catch (Exception e) {
//                throw new RuntimeException("Failed to resolve hostname: " + HOST + " , " + e.getLocalizedMessage());
                HHLog.d("Failed to resolve hostname: " + HOST + " , " + e.getLocalizedMessage());
                new Handler(Looper.getMainLooper()).post(() -> {
                    callback.onResult(HOST);
                });
            }
        }).start();
    }

    public interface Http3DnsCallback {
        public void onResult(String ipAddr);
    }
}
